#include "head.cuh"

#include <vector>
#include <iomanip>
#include <fstream>


bool read_data_2_matrix(float *UIview, 
	float *UIview_test, 
	const float split_rate){	
	FILE *fh1;
	fh1 = fopen(UIviewFileName, "r");
	if (fh1 == NULL){
		return false;
	}
	for (int i = 0; i < nUsers*nItems; ++i){
		UIview[i] = 0.0; 
	}
	for (int i = 0; i < nUsers*nItems; ++i){ 
		UIview_test[i] = 0.0; 
	}
	int row = 0;
	int col = 0;
	float val = 0.0;


	fseek(fh1, 0, SEEK_SET);
	std::vector<std::pair<int, float>> tv;
	int start_index = 0;
	while (EOF != fscanf(fh1, "%u%u%f\n", &row, &col, &val)){
		if (start_index == row){
			tv.push_back(std::make_pair(col, val));
		}
		else{
			std::random_shuffle(tv.begin(), tv.end());
			int train_part = (int)(tv.size()*split_rate);
			int i = 0;
			for (; i < train_part; i++){
				UIview[IDX2C(start_index, tv[i].first, nUsers)] = tv[i].second;
			}
			for (; i < tv.size(); i++){
				UIview_test[IDX2C(start_index, tv[i].first, nUsers)] = tv[i].second;
			}
			start_index = row;
			tv.clear();
			tv.push_back(std::make_pair(col, val));
		}

	}
	std::random_shuffle(tv.begin(), tv.end());
	int train_part = (int)(tv.size()*split_rate);
	int i = 0;
	for (; i < train_part; i++){
		UIview[IDX2C(row, tv[i].first, nUsers)] = tv[i].second;
	}
	for (; i < tv.size(); i++){
		UIview_test[IDX2C(row, tv[i].first, nUsers)] = tv[i].second;
	}
	tv.erase(tv.begin(), tv.end());
	fclose(fh1);

	return true;
}


void write_test_data(const float *UIview_test,
	const int m,
	const int n,
	const char * filename){
	FILE *f;
	f = fopen(filename, "w");
	for (int i = 0; i < m; i++){
		for (int j = 0; j < n; j++){
			if (UIview_test[i+j*m]>0)
				fprintf(f,"%d %d %.1f\n",i,j, UIview_test[i+j*m]);
		}
	}
	fclose(f);
}


void write_into_file(float *B, const int r, const int n, const char *filename){
	FILE *f;
	f = fopen(filename, "w");
	std::stringstream ss;
	for (int i = 0; i < n; i++){
		ss.str("");
		for (int j = 0; j < r; j++){
			ss << B[j + r*i]<<" ";
		}
		ss << "\n";
		fprintf(f, "%s", ss.str().c_str());
	}
	fclose(f);
}
